package com.rex.saas.interceptor;


import com.rex.saas.bean.BaseResponse;
import com.rex.saas.bean.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhusiyu11000
 * @description: 异常拦截处理器
 * @date 2020-01-09
 */

@RestControllerAdvice
@Slf4j
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = Exception.class)
    public BaseResponse handleException(Exception e, HttpServletRequest httpServletRequest) {
        //自定义异常
        BaseResponse resultVO = null;
        if (e instanceof HttpClientErrorException) {
            log.error("HttpClientErrorException ", e);
            if(((HttpClientErrorException) e).getStatusCode().value() == HttpStatus.UNAUTHORIZED.value()){
                resultVO = BaseResponse.error(ResultCode.TOKEN_ERROR.getStatus(), ResultCode.TOKEN_ERROR.getMessage() +" : " + e.getMessage());
            }else {
                resultVO = BaseResponse.error(ResultCode.HTTP_ERROR.getStatus(), ResultCode.HTTP_ERROR.getMessage() +" : " + e.getMessage());
            }
        } else if (e instanceof MissingServletRequestParameterException) {
            log.error("缺少请求参数, url:{}", httpServletRequest.getRequestURI(), e);
            resultVO = BaseResponse.error(ResultCode.PARAM_ERROR.getStatus(), ResultCode.PARAM_ERROR.getMessage() +" : " + e.getMessage());
        } else {
            log.error("系统异常, url:{}", httpServletRequest.getRequestURI(), e);
            resultVO = BaseResponse.error(ResultCode.SYSTEM_ERROR.getStatus(), e.getMessage());
        }
        return resultVO;
    }
}
